package servletAction;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.context.ApplicationContext;

import util.DomainUtils;
import util.FormArgumentsException;
import actionForm.SearchContactValidationForm;
import domain.dao.interfaces.IDAOContact;
import domain.entities.interfaces.IContact;

public class SearchContactAction 
extends Action {
	
	public ActionForward execute(final ActionMapping pMapping,
			ActionForm pForm, final HttpServletRequest pRequest,
			final HttpServletResponse pResponse) {
		final SearchContactValidationForm lForm = (SearchContactValidationForm) pForm;
		
		String keywords = lForm.getKeywords();
		
		ApplicationContext context = util.SpringUtils.getApplicationContext();

		try {
			IDAOContact daoContact = (IDAOContact) context.getBean("beanDAOContact");
			List<IContact> contacts = daoContact.searchContact(keywords.split(" "));
					
			pRequest.setAttribute(DomainUtils.SEARCH_CONTACT_RESULT, contacts);

			DomainUtils.displayInfoMessage(
					pRequest, 
					DomainUtils.SHOW_CONTACT_ALERT_CURRENT_COLOR, 
					"The research has finished successfully.");
		}
		catch(Exception e) {

			if((e instanceof FormArgumentsException) == false) {
				pRequest.setAttribute(DomainUtils.ALERT_ERROR_STRING, "An error occur on the server.");
			}
		}
		

		pRequest.setAttribute("keywords", keywords);
		
		return pMapping.findForward("stay");
	}
}
